package com.imooc.distributedemo.resume.leetcode;

import org.redisson.misc.Hash;

import java.util.Deque;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Set;

public class SolutionLongestUniqueSubarray {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 1, 2, 3, 4, 5, 2};
        int num = maxLength(arr);
    }

    /**
     * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
     *
     *
     * @param arr int整型一维数组 the array
     * @return int整型
     */
    public static int maxLength (int[] arr) {
        // write code here
        if(null==arr||arr.length==0){
            return 0;
        }
        int maxLength = 0;
        Deque<Integer> deque = new LinkedList<>();
        Set<Integer> set = new HashSet<>();
        int left = 0;

        for (int right = 0; right < arr.length; right++) {
            int currentNum = arr[right];
            if(set.contains(currentNum)){
                // 当前数字已经出现过，则移动左侧边界
                while(!deque.isEmpty()&&set.contains(arr[left])){
                    set.remove(arr[left]);
                    deque.pollFirst();
                    left++;
                }
            }
            // 添加当前数字到集合和队列
            set.add(currentNum);
            deque.offerLast(currentNum);
            //更新最长长度
            maxLength = Math.max(maxLength,right-left+1);
        }
        return maxLength;
    }
}
